package com.angcyo.uiview.less.recycler.adapter;

import android.content.Context;
import android.os.Handler;
import android.os.Looper;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.v7.util.DiffUtil;
import android.support.v7.widget.RecyclerView;
import android.text.TextUtils;
import android.util.SparseIntArray;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewGroup;
import com.angcyo.http.Rx;
import com.angcyo.lib.L;
import com.angcyo.uiview.less.base.BaseUI;
import com.angcyo.uiview.less.recycler.RBaseViewHolder;
import com.angcyo.uiview.less.recycler.RRecyclerView;
import com.angcyo.uiview.less.recycler.widget.ILoadMore;
import com.angcyo.uiview.less.recycler.widget.IShowState;
import com.angcyo.uiview.less.recycler.widget.ItemShowStateLayout;
import com.angcyo.uiview.less.utils.RUtils;
import rx.Observer;
import rx.functions.Action1;
import rx.functions.Func2;
import rx.observables.SyncOnSubscribe;

import java.util.ArrayList;
import java.util.List;

/**
 * Created by angcyo on 16-01-18-018.
 */
public abstract class RBaseAdapter<T> extends RecyclerView.Adapter<RBaseViewHolder>
        implements RecyclerView.OnChildAttachStateChangeListener {

    /**
     * 具有此标识的的item type, 会在GridLayoutManager中, 全行显示
     * <p>
     * 第4位的最高字节  0x8000 = 32,768
     */
    public static final int ITEM_SINGLE_LINE = 0x8_000;

    public static final int ITEM_TYPE_LOAD_MORE = 666 | ITEM_SINGLE_LINE;
    public static final int ITEM_TYPE_SHOW_STATE = 667 | ITEM_SINGLE_LINE;
    public RecyclerView recyclerView;
    protected List<T> mAllDatas;
    protected Context mContext;
    /**
     * 是否激活加载更多
     */
    protected boolean mEnableLoadMore = false;
    /**
     * 当调用setLoadMoreEnd时, 是否自动开启mEnableLoadMore
     */
    protected boolean mAutoEnableLoadMore = true;
    /**
     * 激活加载到倒数第几个item时, 回调加载更多, 此值需要mEnableLoadMore=true
     * -1, 表示关闭
     */
    protected int mEnableLoadMoreWithLastIndex = -1;
    protected ILoadMore mLoadMoreView;
    protected OnAdapterLoadMoreListener<T> mLoadMoreListener;
    /**
     * 是否激活布局状态显示, 可以在Item中显示,空布局, 无网络布局, 加载中布局,和错误布局
     */
    protected boolean mEnableShowState = true;
    protected IShowState mIShowState;
    protected Handler handler;
    /**
     * 界面定制处理接口
     */
    protected BaseUI.UIAdapterLoadMore uiAdapterLoadMore;
    protected BaseUI.UIAdapterShowStatus uiAdapterShowStatus;
    /**
     * 保存 itemType 对应的 layout id
     */
    protected SparseIntArray layouts = new SparseIntArray();
    /**
     * 当前加载状态
     */
    int mLoadState = ILoadMore.NORMAL;
    /**
     * 当前显示的状态
     */
    int mShowState = IShowState.NORMAL;
    /**
     * 切换显示状态, 是否执行动画
     */
    boolean animToShowState = false;

    public RBaseAdapter() {
        this(null);
    }

    public RBaseAdapter(Context context) {
        this(context, null);
    }

    //<editor-fold desc="静态方法区">

    public RBaseAdapter(Context context, List<T> datas) {
        this.mAllDatas = datas == null ? new ArrayList<T>() : datas;
        this.mContext = context;
        handler = new Handler(Looper.getMainLooper());
        registerLayouts(layouts);
    }

    public static int getListSize(List list) {
        return list == null ? 0 : list.size();
    }

    //</editor-fold desc="静态方法区">

    //<editor-fold desc="生命周期方法">

    /**
     * 使用布局局部刷新
     */
    public static void localRefresh(RecyclerView recyclerView, OnLocalRefresh localRefresh) {
        if (recyclerView == null || localRefresh == null) {
            return;
        }
        int childCount = recyclerView.getChildCount();
        for (int i = 0; i < childCount; i++) {
            View child = recyclerView.getChildAt(i);
            ViewGroup.LayoutParams params = child.getLayoutParams();
            if (params instanceof RecyclerView.LayoutParams) {
                //https://stackoverflow.com/questions/29684154/recyclerview-viewholder-getlayoutposition-vs-getadapterposition
                int layoutPosition = ((RecyclerView.LayoutParams) params).getViewLayoutPosition();

                //当notifyDataSetChanged调用后, adapterPosition等于-1
                int adapterPosition = ((RecyclerView.LayoutParams) params).getViewAdapterPosition();

                RecyclerView.ViewHolder holder = recyclerView.findViewHolderForLayoutPosition(layoutPosition);
                if (adapterPosition == RecyclerView.NO_POSITION) {
                    adapterPosition = layoutPosition;
                }

                if (holder instanceof RBaseViewHolder) {
                    RBaseViewHolder vh = (RBaseViewHolder) holder;
                    localRefresh.onLocalRefresh(vh, adapterPosition);
                }
            }
        }
    }

    /**
     * 此方法一定会回调, 不管 view 对应的 holder 是否为空
     *
     * @see RecyclerView#dispatchChildAttached
     */
    @Override
    public void onChildViewAttachedToWindow(@NonNull View view) {
        ViewGroup.LayoutParams layoutParams = view.getLayoutParams();
        if (layoutParams instanceof RecyclerView.LayoutParams) {
            int viewAdapterPosition = ((RecyclerView.LayoutParams) layoutParams).getViewAdapterPosition();
            int viewLayoutPosition = ((RecyclerView.LayoutParams) layoutParams).getViewLayoutPosition();
            onChildViewAttachedToWindow(view, viewAdapterPosition, viewLayoutPosition);
        }
    }

    @Override
    public void onChildViewDetachedFromWindow(@NonNull View view) {
        ViewGroup.LayoutParams layoutParams = view.getLayoutParams();
        if (layoutParams instanceof RecyclerView.LayoutParams) {
            int viewAdapterPosition = ((RecyclerView.LayoutParams) layoutParams).getViewAdapterPosition();
            int viewLayoutPosition = ((RecyclerView.LayoutParams) layoutParams).getViewLayoutPosition();
            onChildViewDetachedFromWindow(view, viewAdapterPosition, viewLayoutPosition);
        }
    }

    /**
     * 此方法会保证 holder 不为空
     *
     * @see RecyclerView#dispatchChildAttached
     */
    @Override
    public void onViewAttachedToWindow(@NonNull RBaseViewHolder holder) {
        super.onViewAttachedToWindow(holder);
//        L.w("onViewAttachedToWindow");
    }

    @Override
    public void onViewDetachedFromWindow(@NonNull RBaseViewHolder holder) {
        super.onViewDetachedFromWindow(holder);
//        L.w("onViewDetachedFromWindow");
    }

    //</editor-fold desc="生命周期方法">

    //<editor-fold desc="Adapter 核心方法">

    @Override
    public void onViewRecycled(@NonNull RBaseViewHolder holder) {
        super.onViewRecycled(holder);
        if (holder.getItemViewType() == ITEM_TYPE_LOAD_MORE) {
            mLoadMoreView = null;
        }
        if (holder.getItemViewType() == ITEM_TYPE_SHOW_STATE) {
            mIShowState = null;
        }
    }

    @Override
    public int getItemCount() {
        if (isStateLayout()) {
            return 1;
        }

        int size = mAllDatas == null ? 0 : mAllDatas.size();
        if (mEnableLoadMore) {
            size += 1;
        }
        return size;
    }

    @Override
    final public int getItemViewType(int position) {
        if (isStateLayout()) {
            return ITEM_TYPE_SHOW_STATE;
        }
        if (mEnableLoadMore && isLast(position)) {
            return ITEM_TYPE_LOAD_MORE;
        }
        return getItemType(position);
    }

    @Override
    @NonNull
    public RBaseViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
        View itemView = null;
        RBaseViewHolder viewHolder = null;
        int itemLayoutId = -1;
        try {

            if (mContext == null) {
                L.w("RBaseViewHolder onCreateViewHolder:注意 mContext=null, 已使用parent.getContext()替换");
                mContext = parent.getContext();
            }

            if (mContext == null) {
                throw new NullPointerException("RBaseViewHolder onCreateViewHolder:错误 mContext=null");
            }

            if (mEnableShowState && viewType == ITEM_TYPE_SHOW_STATE) {
                itemView = createShowState(mContext, parent);
                mIShowState = (IShowState) itemView;
            } else if (mEnableLoadMore && viewType == ITEM_TYPE_LOAD_MORE) {
                itemView = createLoadMore(mContext, parent);
                mLoadMoreView = (ILoadMore) itemView;
            } else {
                itemView = createItemView(parent, viewType);
                if (itemView == null) {
                    itemLayoutId = getItemLayoutId(viewType);
                    try {
                        itemView = LayoutInflater.from(mContext).inflate(itemLayoutId, parent, false);
                    } catch (Exception e) {
                        L.e("xml inflate 失败, 请检查自定义View的应用路径.");
                        e.printStackTrace();
                    }
                }
            }
            viewHolder = createBaseViewHolder(viewType, itemView);
        } catch (Exception e) {
            L.e("请及时处理此处BUG#" + viewType + "\nitemView=" + itemView);
            e.printStackTrace();
        }
        if (viewHolder == null) {
            throw new NullPointerException("RBaseViewHolder 创建失败, itemView=" + itemView + " itemLayoutId:" + itemLayoutId);
        }
        return viewHolder;
    }

    @Override
    public void onBindViewHolder(@NonNull RBaseViewHolder holder, int position) {
        //L.e("call: onBindViewHolder([holder, position])-> " + position);
        try {
            if (isStateLayout()) {
                if (holder.getItemViewType() == ITEM_TYPE_SHOW_STATE) {
                    mIShowState = (IShowState) holder.itemView;
                }
//
                if (mIShowState != null) {
                    mIShowState.setShowState(mShowState);
                    onBindShowStateView(holder, mShowState, position);
                }
            } else if (mEnableLoadMore && isLast(position)) {
                /**如果第一个就是加载更多的布局, 需要调用加载更多么?*/
                if (holder.getItemViewType() == ITEM_TYPE_LOAD_MORE) {
                    mLoadMoreView = (ILoadMore) holder.itemView;
                }

                onBindLoadMore(position);
                onBindLoadMoreView(holder, mLoadState, position);
            } else {
                if ((mEnableLoadMoreWithLastIndex > 0 &&
                        (getAllDataCount() - position) <= mEnableLoadMoreWithLastIndex)) {
                    onBindLoadMore(position);
                }
                onBindView(holder, position, mAllDatas.size() > position ? mAllDatas.get(position) : null);
            }
        } catch (Exception e) {
            L.e("请及时处理此处BUG#" + position + "#" + e.getMessage());
            e.printStackTrace();
        }
    }

    //</editor-fold desc="Adapter 核心方法">

    //<editor-fold desc="可操作方法">

    @Override
    final public void onBindViewHolder(RBaseViewHolder holder, int position, List<Object> payloads) {
        super.onBindViewHolder(holder, position, payloads);
        //L.e("call: onBindViewHolder([holder, position, payloads])-> " + position);
    }

    /**
     * 重写此方法需要和{@link #getItemType(int, Object)}配合使用
     * 但是不需要重写{@link #getItemLayoutId(int)}
     */
    protected void registerLayouts(@NonNull SparseIntArray layouts) {

    }

    public RBaseAdapter<T> setOnLoadMoreListener(OnAdapterLoadMoreListener<T> loadMoreListener) {
        mLoadMoreListener = loadMoreListener;
        return this;
    }

    /**
     * 返回是否激活加载更多
     */
    public boolean isEnableLoadMore() {
        return mEnableLoadMore || mEnableLoadMoreWithLastIndex != -1;
    }

    /**
     * 启用加载更多功能
     */
    public void setEnableLoadMore(boolean enableLoadMore) {
        boolean loadMore = mEnableLoadMore;
        mEnableLoadMore = enableLoadMore;

        if (isStateLayout() || loadMore == enableLoadMore) {
            return;
        }

        if (enableLoadMore) {
            notifyItemInserted(getLastPosition());
        } else {
            notifyItemRemoved(getLastPosition());
        }
    }

    //是否该显示状态布局
    protected boolean isStateLayout() {
        return mEnableShowState && mShowState != IShowState.NORMAL;
    }

    @NonNull
    protected RBaseViewHolder createBaseViewHolder(int viewType, View itemView) {
        return new RBaseViewHolder(itemView, viewType);
    }

    /**
     * 创建状态显示切换布局
     * View 需要实现 IShowState 接口
     */
    protected View createShowState(Context context, ViewGroup parent) {
        return getUiAdapterShowStatus().createShowState(this, context, parent);
    }

    /**
     * 创建加载更多布局
     * View 需要实现 ILoadMore 接口
     */
    protected View createLoadMore(Context context, ViewGroup parent) {
        return getUiAdapterLoadMore().createLoadMore(this, context, parent);
    }

    /**
     * 直接从data 列表索引拿数据
     */
    public T getDataByIndex(int position) {
        return getAllDatas().size() > position ? mAllDatas.get(position) : null;
    }

    /**
     * 不同的状态, 显示不同的布局
     * <p>
     * R.layout.base_item_show_state_layout
     */
    protected void onBindShowStateView(@NonNull RBaseViewHolder holder, int showState, int position) {
        getUiAdapterShowStatus().onBindShowStateView(this, holder, showState, position);
    }

    /**
     * @see #onBindLoadMoreView(RBaseViewHolder, int, int)
     * R.layout.base_item_load_more_layout
     */
    @Deprecated
    private void onBindLoadMore(int position) {
        if (mLoadState == ILoadMore.NORMAL
                || mLoadState == ILoadMore.LOAD_ERROR) {

            /**如果第一个就是加载更多的布局, 需要调用加载更多么?*/
            if (position != 0) {
                mLoadState = ILoadMore.LOAD_MORE;

                //触发加载更多回调
                handler.post(new Runnable() {
                    @Override
                    public void run() {
                        onLoadMore();
                        if (mLoadMoreListener != null) {
                            mLoadMoreListener.onAdapterLodeMore(RBaseAdapter.this);
                        }
                    }
                });
            }
        }

        updateLoadMoreView();
    }

    /**
     * 重写此方法, 可以修改加载更多视图
     */
    protected void onBindLoadMoreView(@NonNull RBaseViewHolder holder, int loadState, int position) {
        getUiAdapterLoadMore().onBindLoadMoreView(this, holder, loadState, position);
    }

    private void updateLoadMoreView() {
        if (mLoadMoreView != null) {
            mLoadMoreView.setLoadState(mLoadState);

            if (mLoadState == ILoadMore.NORMAL) {
                //当前布局已经在界面中, 又重新出发了加载更多
                notifyItemChanged(getLastPosition());
            }
        }
    }

    /**
     * 重写此方法, 实现加载更多功能
     */
    protected void onLoadMore() {

    }

    public void adapterRefresh() {
        onAdapterRefresh();

        if (mLoadMoreListener != null && mLoadMoreListener.onAdapterRefresh(this)) {

        } else {
            setShowState(IShowState.LOADING);
        }
    }

    /**
     * 情感图显示错误时, 触发的刷新
     */
    public void onAdapterRefresh() {

    }

    /**
     * 结束加载更多的标识, 方便下一次回调
     */
    public void setLoadMoreEnd() {
        if (mLoadMoreView != null && mLoadState == ILoadMore.NO_MORE) {
            //如果当前界面上已经是没有更多的状态
            return;
        }

        mLoadState = ILoadMore.NORMAL;
        if (mAutoEnableLoadMore) {
            setEnableLoadMore(true);
        }
        updateLoadMoreView();
    }

    public void setLoadError() {
        mLoadState = ILoadMore.LOAD_ERROR;
        if (mAutoEnableLoadMore) {
            setEnableLoadMore(true);
        }
        updateLoadMoreView();
    }

    public void setNoMore() {
        setNoMore(false);
    }

    public void setNoMore(boolean refresh) {
        mLoadState = ILoadMore.NO_MORE;
        if (mAutoEnableLoadMore) {
            setEnableLoadMore(true);
        }
        if (refresh) {
            updateLoadMoreView();//不需要及时刷新
        }
    }

    public int getLoadState() {
        return mLoadState;
    }

    public boolean isLast(int position) {
        if (position < 0) {
            return false;
        }
        return position == getLastPosition();
    }

    public boolean isBaseDataLast(int posInData) {
        if (posInData < 0) {
            return false;
        }
        return posInData == getDataLastPosition();
    }

    private int getLastPosition() {
        return getItemCount() - 1;
    }

    private int getDataLastPosition() {
        int dataSize = mAllDatas == null ? 0 : mAllDatas.size();
        return dataSize - 1;
    }

    /**
     * 数据是否为空
     */
    public boolean isItemEmpty() {
        return mAllDatas == null || mAllDatas.isEmpty();
    }

    /**
     * 根据position返回Item的类型.
     */
    public int getItemType(int position) {
        T data = null;
        if (mAllDatas != null) {
            data = mAllDatas.size() > position ? mAllDatas.get(position) : null;
        }
        return getItemType(position, data);
    }

    public int getItemType(int position, @Nullable T data) {
        return 0;
    }

    /**
     * 获取数据的数量
     */
    public int getAllDataCount() {
        return mAllDatas == null ? 0 : mAllDatas.size();
    }

    //---------------滚动事件的处理--------------------//

    /**
     * 当 {@link #getItemLayoutId(int)} 返回0的时候, 会调用此方法
     */
    protected View createItemView(ViewGroup parent, int viewType) {
        return null;
    }

    /**
     * 如果未重写 {@link #registerLayouts(SparseIntArray)}, 请重写此方法
     */
    protected int getItemLayoutId(int viewType) {
        return layouts.get(viewType);
    }

    //----------------Item 数据的操作-----------------//

    protected abstract void onBindView(@NonNull RBaseViewHolder holder, int position, @Nullable T bean);

    public void onScrollStateChanged(@NonNull RRecyclerView recyclerView, int newState) {
    }

    public void onScrolled(@NonNull RRecyclerView recyclerView, int dx, int dy) {
    }

    public void onScrolledInTouch(@NonNull RRecyclerView recyclerView,
                                  MotionEvent e1, MotionEvent e2,
                                  float distanceX, float distanceY) {
    }

    /**
     * 在最后的位置插入数据
     */
    public void addLastItem(T bean) {
        if (mAllDatas == null) {
            mAllDatas = new ArrayList<>();
        }
        int startPosition = mAllDatas.size();
        mAllDatas.add(bean);
        notifyItemInserted(startPosition);
        notifyItemRangeChanged(startPosition, getItemCount());
    }

    /**
     * 解决九宫格添加图片后,添加按钮消失时崩溃的bug
     */
    public void addLastItemSafe(T bean) {
        if (mAllDatas == null) {
            mAllDatas = new ArrayList<>();
        }

        int startPosition = mAllDatas.size();
        mAllDatas.add(bean);
        int itemCount = getItemCount();
        if (itemCount > startPosition + 1) {
            notifyItemInserted(startPosition);
            notifyItemRangeChanged(startPosition, getItemCount());
        } else {
            notifyItemChanged(itemCount - 1);//
        }
    }

    public void addFirstItem(T bean) {
        insertItem(0, bean);
    }

    public void insertItem(int position, T bean) {
        if (mAllDatas == null) {
            mAllDatas = new ArrayList<>();
        }
        mAllDatas.add(position, bean);
        notifyItemInserted(position);
        notifyItemRangeChanged(position, getItemCount());
    }

    /**
     * delete item with object
     */
    public void deleteItem(T bean) {
        if (mAllDatas != null) {
            int indexOf = mAllDatas.indexOf(bean);
            if (indexOf > -1) {
                deleteItem(indexOf);
            }
        }
    }

    public void deleteItem(int position) {
        if (mAllDatas != null) {
            int size = getItemCount();
            if (size > position) {
                if (onDeleteItem(position)) {
                    mAllDatas.remove(position);
                    notifyItemRemoved(position);
                    notifyItemRangeChanged(position, size - position);

                    onDeleteItemEnd(position);
                }
            }
        }
    }

    /**
     * Item删除成功结束后
     */
    protected void onDeleteItemEnd(int position) {

    }

    /**
     * 删除最后一个item
     */
    public void deleteLastItem() {
        if (mAllDatas != null) {
            int allDataCount = getAllDataCount();
            if (allDataCount > 0) {
                deleteItem(allDataCount - 1);
            }
        }
    }

    /**
     * 获取最后一个Item
     */
    public T getLastItem() {
        T result = null;
        if (!RUtils.isListEmpty(mAllDatas)) {
            result = mAllDatas.get(mAllDatas.size() - 1);
        }
        return result;
    }

    public T getItemData(int position) {
        T result = null;
        if (!RUtils.isListEmpty(mAllDatas)) {
            if (mAllDatas.size() > position) {
                result = mAllDatas.get(position);
            }
        }
        return result;
    }

    /**
     * 是否可以删除bean
     */
    protected boolean onDeleteItem(int position) {
        return true;
    }

    public void removeFirstItem() {
        mAllDatas.remove(0);
        notifyItemRemoved(0);
        notifyItemRangeChanged(0, getItemCount());
    }

    public void removeLastItem() {
        int last = mAllDatas.size() - 1;
        mAllDatas.remove(last);
        notifyItemRemoved(last);
        notifyItemRangeChanged(last, getItemCount());
    }

    /**
     * 重置数据
     */
    public void resetData(List<T> datas) {
        resetData(null, datas);
    }

    public void resetData(@Nullable final RecyclerView recyclerView, final List<T> datas) {
        if (recyclerView != null && recyclerView.isComputingLayout()) {
            recyclerView.post(new Runnable() {
                @Override
                public void run() {
                    resetData(recyclerView, datas);
                }
            });
            return;
        }

        int oldSize = getListSize(mAllDatas);
        int newSize = getListSize(datas);

        if (datas == null) {
            this.mAllDatas = new ArrayList<>();
        } else {
            this.mAllDatas = datas;
        }
        if (oldSize == newSize && newSize > 0) {
            if (isEnableLoadMore()) {
                oldSize += 1;
            }
            notifyItemRangeChanged(0, oldSize);
        } else {
            notifyDataSetChanged();
        }
    }

    public void resetData(boolean async, List<T> datas, RDiffCallback<T> diffCallback) {
        if (async) {
            resetDataAsync(datas, diffCallback);
        } else {
            resetData(datas, diffCallback);
        }
    }

    public void resetData(List<T> datas, RDiffCallback<T> diffCallback) {
        if (RUtils.isListEmpty(datas)) {
            resetData(datas);
            return;
        }

        DiffUtil.DiffResult diffResult = DiffUtil.calculateDiff(new RDiffCallback<>(mAllDatas, datas, diffCallback));
        this.mAllDatas = datas;
        diffResult.dispatchUpdatesTo(this);
    }

    public void resetDataAsync(final List<T> datas, final RDiffCallback<T> diffCallback) {
        if (RUtils.isListEmpty(datas)) {
            resetData(datas);
            return;
        }

        Rx.create(new SyncOnSubscribe<Integer, DiffUtil.DiffResult>() {
            @Override
            protected Integer generateState() {
                return 1;
            }

            @Override
            protected Integer next(Integer state, Observer<? super DiffUtil.DiffResult> observer) {
                if (state > 0) {
                    DiffUtil.DiffResult diffResult = DiffUtil.calculateDiff(new RDiffCallback<>(mAllDatas, datas, diffCallback));
                    observer.onNext(diffResult);
                } else {
                    observer.onCompleted();
                }
                return 0;
            }
        }).compose(Rx.<DiffUtil.DiffResult>transformer())
                .subscribe(new Action1<DiffUtil.DiffResult>() {
                    @Override
                    public void call(DiffUtil.DiffResult diffResult) {
                        RBaseAdapter.this.mAllDatas = datas;
                        diffResult.dispatchUpdatesTo(RBaseAdapter.this);
                    }
                });
    }

    /**
     * 追加数据
     */
    public void appendData(List<T> datas) {
        if (datas == null || datas.size() == 0) {
            return;
        }
        if (this.mAllDatas == null) {
            this.mAllDatas = new ArrayList<>();
        }
        int startPosition = this.mAllDatas.size();
        this.mAllDatas.addAll(datas);
        notifyItemRangeInserted(startPosition, datas.size());
        notifyItemRangeChanged(startPosition, getItemCount());
    }

    @NonNull
    public List<T> getAllDatas() {
        if (this.mAllDatas == null) {
            this.mAllDatas = new ArrayList<>();
        }
        return mAllDatas;
    }

    /**
     * 设置布局显示状态
     *
     * @see IShowState
     */
    public void setShowState(int showState) {
        int oldState = this.mShowState;

        if (oldState == showState) {
            return;
        }
        this.mShowState = showState;

        if (isEnableLoadMore()) {
            setLoadMoreEnd();
        }

        if (mIShowState == null ||
                oldState == IShowState.NORMAL ||
                showState == IShowState.NORMAL) {
            if (mIShowState != null &&
                    mIShowState instanceof ItemShowStateLayout) {
                if (animToShowState) {
                    ((ItemShowStateLayout) mIShowState).animToHide(new Runnable() {
                        @Override
                        public void run() {
                            notifyDataSetChanged();
                        }
                    });
                } else {
                    notifyDataSetChanged();
                }
            } else {
                notifyDataSetChanged();
            }
        } else {
            mIShowState.setShowState(showState);
        }
    }

    public boolean isAutoEnableLoadMore() {
        return mAutoEnableLoadMore;
    }

    public void setAutoEnableLoadMore(boolean autoEnableLoadMore) {
        mAutoEnableLoadMore = autoEnableLoadMore;
    }

    protected void onChildViewAttachedToWindow(@NonNull View view, int adapterPosition, int layoutPosition) {
        //L.v("call: onChildViewAttachedToWindow -> " + adapterPosition + " " + layoutPosition + " " + view);
    }

    protected void onChildViewDetachedFromWindow(@NonNull View view, int adapterPosition, int layoutPosition) {
        //L.v("call: onChildViewDetachedFromWindow -> " + adapterPosition + " " + layoutPosition + " " + view);
    }

    public RBaseAdapter<T> setEnableLoadMoreWithLastIndex(int enableLoadMoreWithLastIndex) {
        mEnableLoadMoreWithLastIndex = enableLoadMoreWithLastIndex;
        return this;
    }

    public void onScrollStateEnd(RRecyclerView rRecyclerView, boolean firstItemVisible, boolean lastItemVisible, boolean topCanScroll, boolean bottomCanScroll) {

    }

    /**
     * 判断当前的数据, 是否和之前的数据一样, 用来在区分加载不同数据使用
     */
    public boolean isDataEqualPrev(int posInData, T bean) {
        if (posInData <= 0) {
            return false;
        }
        List<T> allDatas = getAllDatas();
        if (RUtils.isListEmpty(allDatas)) {
            return false;
        }
        T prevData = allDatas.get(posInData - 1);
        return isDataEqual(prevData, bean);
    }

    public boolean isDataEqual(T prevData, T data) {
        return prevData == data;
    }

    public boolean isDataEqualPrev(int posInData, T bean, Func2<T, T, Boolean> equal) {
        if (posInData <= 0) {
            return false;
        }
        List<T> allDatas = getAllDatas();
        if (RUtils.isListEmpty(allDatas)) {
            return false;
        }
        T prevData = allDatas.get(posInData - 1);
        return equal.call(prevData, bean);
    }

    /**
     * 刷新某一个item
     */
    public void notifyItemChanged(T item) {
        if (RUtils.isListEmpty(mAllDatas)) {
            return;
        }
        int indexOf = mAllDatas.indexOf(item);
        if (indexOf > -1) {
            notifyItemChanged(indexOf);
        }
    }

    public void notifyItemInsertedAndUpdate(int position) {
        notifyItemInserted(position);
        notifyItemRangeChanged(position, getItemCount());
    }

//    /**
//     * Item悬停库的支持
//     */
//    @Override
//    public List<?> getAdapterData() {
//        return mAllDatas;
//    }

    /**
     * 自动处理分页加载, 和加载更多的数据
     */
    @Deprecated
    public void onUILoadData(int page /*分页*/, int pageSize /*每一页数量*/, List<T> datas /*数据*/) {
        boolean isDataListEmpty = RUtils.isListEmpty(datas);
        if (isDataListEmpty) {
            if (page <= 1) {
                if (onUILoadDataEmpty()) {
                    return;
                }
            }
        } else {
            setShowState(IShowState.NORMAL);
        }

        if (page <= 1) {
            resetData(datas);

            if (isDataListEmpty) {
                setEnableLoadMore(false);
            } else if (datas.size() >= pageSize) {
                if (mAutoEnableLoadMore) {
                    setEnableLoadMore(true);
                }
            }
        } else {
            if (isDataListEmpty) {
                if (isEnableLoadMore()) {
                    setNoMore(true);
                }
            } else {
                appendData(datas);
                if (datas.size() >= pageSize) {
                    if (isEnableLoadMore()) {
                        setLoadMoreEnd();
                    }
                } else {
                    if (isEnableLoadMore()) {
                        setNoMore(true);
                    }
                }
            }
        }
    }

    @Deprecated
    public void onUILoadDataSet(int page /*分页*/, int pageSize /*每一页数量*/, int datasSize /*数据数量*/) {
        if (page <= 1) {
            if (datasSize < pageSize) {
                setEnableLoadMore(false);
            } else if (datasSize >= pageSize) {
                if (mAutoEnableLoadMore) {
                    setEnableLoadMore(true);
                }
            }
        } else {
            if (datasSize < pageSize) {
                if (isEnableLoadMore()) {
                    setNoMore(true);
                }
            } else {
                if (datasSize >= pageSize) {
                    if (isEnableLoadMore()) {
                        setLoadMoreEnd();
                    }
                } else {
                    if (isEnableLoadMore()) {
                        setNoMore(true);
                    }
                }
            }
        }
    }

    public boolean onUILoadDataEmpty() {
        return false;
    }

    /**
     * 更新所有item
     */
    public void updateAllItem() {
        notifyItemRangeChanged(0, getAllDataCount());
    }

    /**
     * 加载更多结束的处理
     */
    public void loadMoreEnd(List<T> datas /*当前返回的数据列表*/,
                            int currentPage /*当前第几页*/,
                            int pageSize /*每页加载最多多少数据*/) {
        int listSize = RUtils.listSize(datas);
        if (currentPage <= 1) {
            //首页
            if (listSize < pageSize) {
                //数据不够, 关闭加载更多功能
                setEnableLoadMore(false);
                onFirstPageSetData(datas);
            } else {
                onFirstPageSetData(datas);
                if (isEnableLoadMore()) {
                    mLoadState = ILoadMore.NORMAL;
                    setLoadMoreEnd();
                } else {
                    setEnableLoadMore(true);
                }
            }
        } else {
            //其他页
            onOtherPageSetData(datas);

            if (listSize < pageSize) {
                //数据不够, 关闭加载更多功能
                setNoMore(listSize == 0);
            } else {
                setLoadMoreEnd();
            }
        }
    }

    /**
     * 加载更多失败
     */
    public void loadMoreError() {
        if (isEnableLoadMore()) {
            setLoadError();
        }
    }

    /**
     * 兼容ExItemAdatper
     */
    public void onFirstPageSetData(List<T> datas) {
        resetData(datas);
        if (RUtils.isListEmpty(datas)) {
            if (isEnableShowState()) {
                setShowState(IShowState.EMPTY);
            }
        } else {
            if (isEnableShowState()) {
                setShowState(IShowState.NORMAL);
            }
        }
    }

    public void onOtherPageSetData(List<T> datas) {
        appendData(datas);
    }

    public boolean isEnableShowState() {
        return mEnableShowState;
    }

    //</editor-fold desc="可操作方法">

    //<editor-fold desc="事件回调">

    /**
     * 空布局, 无网络布局, 加载中布局,和错误布局
     */
    public void setEnableShowState(boolean enableShowState) {
        mEnableShowState = enableShowState;
    }

    public BaseUI.UIAdapterLoadMore getUiAdapterLoadMore() {
        if (uiAdapterLoadMore == null) {
            return BaseUI.uiAdapterLoadMore;
        }
        return uiAdapterLoadMore;
    }

    public void setUiAdapterLoadMore(BaseUI.UIAdapterLoadMore uiAdapterLoadMore) {
        this.uiAdapterLoadMore = uiAdapterLoadMore;
    }

    //</editor-fold desc="事件回调">

    //<editor-fold desc="页面样式定制">

    public BaseUI.UIAdapterShowStatus getUiAdapterShowStatus() {
        if (uiAdapterShowStatus == null) {
            return BaseUI.uiAdapterShowStatus;
        }
        return uiAdapterShowStatus;
    }

    public void setUiAdapterShowStatus(BaseUI.UIAdapterShowStatus uiAdapterShowStatus) {
        this.uiAdapterShowStatus = uiAdapterShowStatus;
    }

    @Override
    public void onAttachedToRecyclerView(@NonNull RecyclerView recyclerView) {
        super.onAttachedToRecyclerView(recyclerView);
        this.recyclerView = recyclerView;
    }

    @Override
    public void onDetachedFromRecyclerView(@NonNull RecyclerView recyclerView) {
        super.onDetachedFromRecyclerView(recyclerView);
        this.recyclerView = null;
    }

    //</editor-fold desc="页面样式定制">

    public interface OnAdapterLoadMoreListener<T> {
        void onAdapterLodeMore(@NonNull RBaseAdapter<T> baseAdapter);

        /**
         * 情感图触发的刷新事件
         *
         * @return true 拦截默认的情感图切换
         */
        boolean onAdapterRefresh(@NonNull RBaseAdapter<T> baseAdapter);
    }

    public interface OnLocalRefresh {
        void onLocalRefresh(RBaseViewHolder viewHolder, int position);
    }

    public static class RDiffCallback<T> extends DiffUtil.Callback {
        List<T> oldDatas;
        List<T> newDatas;
        RDiffCallback<T> mDiffCallback;

        public RDiffCallback() {
        }

        public RDiffCallback(List<T> oldDatas, List<T> newDatas, RDiffCallback<T> diffCallback) {
            this.oldDatas = oldDatas;
            this.newDatas = newDatas;
            mDiffCallback = diffCallback;
        }

        @Override
        public int getOldListSize() {
            return getListSize(oldDatas);
        }

        @Override
        public int getNewListSize() {
            return getListSize(newDatas);
        }

        @Nullable
        @Override
        public Object getChangePayload(int oldItemPosition, int newItemPosition) {
            return super.getChangePayload(oldItemPosition, newItemPosition);
        }

        @Override
        public boolean areItemsTheSame(int oldItemPosition, int newItemPosition) {
            return mDiffCallback.areItemsTheSame(oldDatas.get(oldItemPosition), newDatas.get(newItemPosition));
        }

        /**
         * 被DiffUtil调用，用来检查 两个item是否含有相同的数据
         * 这个方法仅仅在areItemsTheSame()返回true时，才调用。
         */
        @Override
        public boolean areContentsTheSame(int oldItemPosition, int newItemPosition) {
            return mDiffCallback.areContentsTheSame(oldDatas.get(oldItemPosition), newDatas.get(newItemPosition));
        }

        /**
         * 重写此方法, 判断数据是否相等,
         * 如果item不相同, 会先调用 notifyItemRangeRemoved, 再调用 notifyItemRangeInserted
         */
        public boolean areItemsTheSame(@NonNull T oldData, @NonNull T newData) {
            Class<?> oldClass = oldData.getClass();
            Class<?> newClass = newData.getClass();
            if (oldClass.isAssignableFrom(newClass) || newClass.isAssignableFrom(oldClass)) {
                return true;
            }
            return TextUtils.equals(oldClass.getSimpleName(), newClass.getSimpleName());
        }

        /**
         * 重写此方法, 判断内容是否相等,
         * 如果内容不相等, 会调用notifyItemRangeChanged
         */
        public boolean areContentsTheSame(@NonNull T oldData, @NonNull T newData) {
            Class<?> oldClass = oldData.getClass();
            Class<?> newClass = newData.getClass();
            if (oldClass.isAssignableFrom(newClass) ||
                    newClass.isAssignableFrom(oldClass) ||
                    TextUtils.equals(oldClass.getSimpleName(), newClass.getSimpleName())) {
                return oldData.equals(newData);
            }
            return false;
        }
    }
}
